package com.icss.ah.shop.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.login.bean.UserInfoBean;

/**
 * 店铺申请Action
 * @author sw
 *
 */
@Controller
@Scope("prototype")
public class JfShoppingAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;

	public String toGetDetailShopInf() {
		return "toGetDetailShopInf";
	}
	
	/**
	 * 商铺首页展示
	 */
	public void getDetailShopInf() {
		request = this.getRequest();
		String type = request.getParameter("type");//1:最近7天，2：最近一个月，3：最近半年，4：最近一年
		JSONObject obj = new JSONObject();
		Map<String,Object> paraMap = new HashMap<String,Object>(5);
		try {
			String userCode = getUserCodeFromSession();
			UserInfoBean userInfo = getUserInfo(userCode);
			paraMap.put("personAccount", userCode);
			paraMap.put("corpId", userInfo.getCorpId());
			//商铺基本信息
			Map<String,Object> shopInf = jfShoppingService.getShopBasicInf(paraMap);
			if(null != shopInf) {
				paraMap.put("shopId", shopInf.get("SHOP_ID"));
				//访问人数
				Map<String,Object> visitMap = jfShoppingService.getVisitShopInf(paraMap);
				//查询最近7天、一个月、半年、一年订单数量
				Map<String,Object> orderMap = jfShoppingService.getOrderByDate(paraMap);
				obj.putAll(visitMap);
				obj.putAll(orderMap);
				List<Map<String,Object>> praiseList = new ArrayList<Map<String,Object>>();//好评
				List<Map<String,Object>> middleScoreList = new ArrayList<Map<String,Object>>();//中评
				List<Map<String,Object>> badScoreList = new ArrayList<Map<String,Object>>();//差评
				List<Map<String,Object>> list = null;
				
				
				
				if("1".equals(type)) { //最近7天商品销售汇总
					list = jfShoppingService.get7DaysOrderInf(paraMap);
					judgeOrderList(list,praiseList,middleScoreList,badScoreList);
				} else if ("2".equals(type)) { //最近一个月商品销售汇总
					list = jfShoppingService.getMonthDaysOrderInf(paraMap);
					judgeOrderList(list,praiseList,middleScoreList,badScoreList);
				} else if ("3".equals(type)) { //最近半年商品销售汇总
					list = jfShoppingService.getHalfYearDaysOrderInf(paraMap);
					judgeOrderList(list,praiseList,middleScoreList,badScoreList);
				} else if ("4".equals(type)) { //最近一年商品销售汇总
					list = jfShoppingService.getYearDaysOrderInf(paraMap);
					judgeOrderList(list,praiseList,middleScoreList,badScoreList);
				}
//				//商品汇总信息分析
//				paraMap.put("evalValId", "1001");
//				Map<String,Object> detail = jfShoppingService.getOrderDetailInf(paraMap);
//				Map<String,Object> compareMap = compareSummryOrder(visitMap,detail,paraMap);
				obj.putAll(shopInf);
//				obj.putAll(compareMap);
//				obj.putAll(detail);
				obj.put("praiseList", praiseList);
				obj.put("middleScoreList", middleScoreList);
				obj.put("badScoreList", badScoreList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		str2Resp(obj.toString());
	}
	/**
	 * 根据时间类型查询汇总信息
	 * type 1：日，2：周，3：月，4：年
	 */
	public void getSummaryByDateType() {
		request = this.getRequest();
		String type = request.getParameter("type");//1：日，2：周，3：月，4：年
		String shopId = request.getParameter("shopId");
		JSONObject obj = new JSONObject();
		Map<String,Object> paraMap = new HashMap<String,Object>(5);
		String userCode = getUserCodeFromSession();
		paraMap.put("personAccount", userCode);
		paraMap.put("corpId", getBaseCorpId());
		try {
			paraMap.put("shopId", shopId);
			paraMap.put("dateType", type);
			//访问人数
			Map<String,Object> visitMap = jfShoppingService.getVisitShopInf(paraMap);
			obj.putAll(visitMap);
			//商品汇总信息分析
			Map<String,Object> detail = jfShoppingService.getOrderDetailInf(paraMap);
			Map<String,Object> compareMap = compareSummryOrder(visitMap,detail,paraMap);
			obj.putAll(detail);
			obj.putAll(compareMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		str2Resp(obj.toString());
	}

	/**
	 * 按条件计算增长比率
	 * @param tVMap 访问信息
	 * @param tOMap 商品信息
	 * @param paraMap 查询条件
	 * @return
	 */
	private Map<String, Object> compareSummryOrder(Map<String,Object> tVMap,
			Map<String,Object> tOMap,Map<String,Object> paraMap) {
		Map<String,Object> compareMap = new HashMap<String,Object>(12);
		//商品汇总信息相对昨日的增长比率
		paraMap.put("compareFlag", paraMap.get("dateType"));
		paraMap.remove("dateType");
		Map<String,Object> yVMap = jfShoppingService.getVisitShopInf(paraMap);
		Map<String,Object> yOMap = jfShoppingService.getOrderDetailInf(paraMap);
		
		String riseVisitPercentage="";//浏览次数增长比
		String riseSumRealMoneyPercentage="";//总金额增长比
		String riseSumOrderPercentage="";//订单总笔数增长比
		String riseSumProductSortPercentage="";//销售总商品（种）
		//浏览次数上升比
		riseVisitPercentage=getAddPercentage("visitNum", tVMap, yVMap);
		
		//总金额增长比
		riseSumRealMoneyPercentage=getAddPercentage("sumRealMoney", tOMap, yOMap);
		
		//订单总数增长比
		riseSumOrderPercentage=getAddPercentage("sumOrder", tOMap, yOMap);
		
		//销售总商品（种）增长比
		riseSumProductSortPercentage=getAddPercentage("sumSellProductSort", tOMap, yOMap);
		
		//浏览总量上升值
		//long riseVisitCnt = Long.parseLong(tVMap.get("visitCnt").toString()) - 
		//		Long.parseLong(yVMap.get("visitCnt").toString());
		
		//汇总销量上升值
				//long riseSellAmount = Long.parseLong(tOMap.get("sumSellAmonut").toString()) - 
				//		Long.parseLong(yOMap.get("sumSellAmonut").toString());
		//总订单上升值
		long riseOrderCnt=Long.parseLong(tOMap.get("sumOrder").toString()) - 
				Long.parseLong(yOMap.get("sumOrder").toString());
		
		//已完成订单上升值
		long riseCompleteOrder = Long.parseLong(tOMap.get("completeOrder").toString()) - 
				Long.parseLong(yOMap.get("completeOrder").toString());
		//退货数量上升值
		long riseReturnOrder = Long.parseLong(tOMap.get("returnOrder").toString()) - 
				Long.parseLong(yOMap.get("returnOrder").toString());
		//已评价上升值
		long riseEvaluateOrder = Long.parseLong(tOMap.get("evaluateOrder").toString()) - 
				Long.parseLong(yOMap.get("evaluateOrder").toString());
		//好评率上升值
		long risePpriseCnt = Long.parseLong(tOMap.get("priseCnt").toString()) - 
				Long.parseLong(yOMap.get("priseCnt").toString());
		
		
		compareMap.put("riseSumProductSortPercentage", riseSumProductSortPercentage);
		compareMap.put("riseVisitPercentage", riseVisitPercentage);
		compareMap.put("riseSumOrderPercentage", riseSumOrderPercentage);
		compareMap.put("riseSumRealMoneyPercentage", riseSumRealMoneyPercentage);
		
		compareMap.put("riseOrderCnt", riseOrderCnt);
		compareMap.put("riseReturnOrder", riseReturnOrder);
		compareMap.put("riseCompleteOrder", riseCompleteOrder);
		compareMap.put("riseEvaluateOrder", riseEvaluateOrder);
		compareMap.put("risePpriseCnt", risePpriseCnt);
		compareMap.put("completeOrder", tOMap.get("completeOrder").toString());//当前已完成订单数量
		compareMap.put("returnOrder", tOMap.get("returnOrder").toString());//当前退货数量
		compareMap.put("evaluateOrder", tOMap.get("evaluateOrder").toString());//当前订单评价数量
		compareMap.put("priseCnt", tOMap.get("priseCnt").toString());//好评率
		return compareMap;
	}
	
	/**
	 * 返回增长比
	 * @param compareString 比较的字段
	 * @param lastMap 过去的信息
	 * @param nowMap 现在的信息
	 */
	private String getAddPercentage(String compareString,Map<String,Object>nowMap ,Map<String,Object> lastMap){
		String result="";
		if(Double.parseDouble(nowMap.get(compareString).toString())==0 && Double.parseDouble(lastMap.get(compareString).toString())==0){
			result="0%";
		}else if(Double.parseDouble(nowMap.get(compareString).toString())!=0 && Double.parseDouble(lastMap.get(compareString).toString())==0){
			result="100%";
		}else{
			double rise=Double.parseDouble(nowMap.get(compareString).toString())-
					Double.parseDouble(lastMap.get(compareString).toString());
			result=getPercentageString(rise,Double.parseDouble(lastMap.get(compareString).toString()));
		}
		return result;
	}
	
	/**
	 * 获取俩数相除的百分比字符串
	 * @param dividend 被除数
	 * @param divisor  除数
	 */
	private String getPercentageString(Double dividend,Double divisor){
		BigDecimal d1=new BigDecimal(dividend);//被除数
		BigDecimal d2=new BigDecimal(divisor);//除数
		BigDecimal result=d1.divide(d2,4, BigDecimal.ROUND_HALF_UP);//相除结果
		DecimalFormat percentage = new DecimalFormat("0.00%");
		return percentage.format(result.doubleValue());
	}
	
	/**
	 * 根据选择汇总销售信息
	 */
	public void summaryOrder() {
		request = this.getRequest();
		String type = request.getParameter("type");//1:最近7天，2：最近一个月，3：最近半年，4：最近一年
		String shopId = request.getParameter("shopId");
		JSONObject obj = new JSONObject();
		Map<String,Object> paraMap = new HashMap<String,Object>(5);
		String userCode = getUserCodeFromSession();
		paraMap.put("personAccount", userCode);
		paraMap.put("corpId", getBaseCorpId());
		paraMap.put("shopId", shopId);
		try {
			List<Map<String,Object>> praiseList = new ArrayList<Map<String,Object>>();//好评
			List<Map<String,Object>> middleScoreList = new ArrayList<Map<String,Object>>();//中评
			List<Map<String,Object>> badScoreList = new ArrayList<Map<String,Object>>();//差评
			List<Map<String,Object>> list = null;
			if("1".equals(type)) { //最近7天商品销售汇总
				list = jfShoppingService.get7DaysOrderInf(paraMap);
				judgeOrderList(list,praiseList,middleScoreList,badScoreList);
			} else if ("2".equals(type)) { //最近一个月商品销售汇总
				list = jfShoppingService.getMonthDaysOrderInf(paraMap);
				judgeOrderList(list,praiseList,middleScoreList,badScoreList);
			} else if ("3".equals(type)) { //最近半年商品销售汇总
				list = jfShoppingService.getHalfYearDaysOrderInf(paraMap);
				judgeOrderList(list,praiseList,middleScoreList,badScoreList);
			} else if ("4".equals(type)) { //最近一年商品销售汇总
				list = jfShoppingService.getYearDaysOrderInf(paraMap);
				judgeOrderList(list,praiseList,middleScoreList,badScoreList);
			}
			
			obj.put("praiseList", praiseList);
			obj.put("middleScoreList", middleScoreList);
			obj.put("badScoreList", badScoreList);
			this.getResponse().getWriter().write(obj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param list  全部评价列表
	 * @param praiseList  好评
	 * @param middleScoreList  中评
	 * @param badScoreList   差评
	 */
	private void judgeOrderList(List<Map<String, Object>> list,List<Map<String,Object>> praiseList,
			List<Map<String,Object>> middleScoreList,List<Map<String,Object>> badScoreList) {
		if(null != list && list.size() > 0) {
			for (Map<String, Object> map : list) {
				String sortNum = String.valueOf(map.get("SORT_NUM"));
				String evalValId = String.valueOf(map.get("EVAL_VAL_ID"));
				if("1".equals(sortNum)) { //好评
					praiseList.add(map);
				} else if("2".equals(sortNum)) { //中评
					middleScoreList.add(map);
				} else if("3".equals(sortNum)) { //差评
					badScoreList.add(map);
				}
			}
		}
	}
	
	
}
